<?php
/**
 * 出售的设备表
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/6/7
 * @copyright PanxSoft Inc.
 */
namespace App\Models\Panx;

use App\Models\Concerns\ScopeFilterable;
use App\Models\Customer\DeviceAccount;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;


/**
 * @property int id
 * @property int num
 * @property int customer_id
 *
 * @property-read Collection|DeviceAccount[] deviceAccounts
 * @property-write Collection|SkinDetector[] skin_detectors
 *
 * @method static self filterDevice($query_data)
 * @method static self filterOperator(?string $operator)
 * @method static self filterCustomerId(?int $customer_id)
 *
 * @mixin Builder
 */
class SellDevice extends Model
{
    use ScopeFilterable;

    protected $table = 'sell_devices';

    protected $guarded = [];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function purchaseDevice()
    {
        return $this->belongsTo(PurchaseDevice::class, 'purchase_device_id', 'id');
    }

    /**
     * @used-by $deviceAccounts
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function deviceAccounts()
    {
        return $this->hasMany(DeviceAccount::class, 'sell_device_id', 'id');
    }

    /**
     * @used-by filterOperator
     * @param Builder $query
     * @param $operator
     * @return Builder
     */
    public function scopeFilterOperator(Builder $query, $operator)
    {
        if (! $operator) return $query;

        return $query->where('operator','like', '%'. $operator.'%');
    }

    /**
     * @used-by filterCustomerId
     * @param Builder $query
     * @param $customer_id
     * @return Builder
     */
    public function scopeFilterCustomerId(Builder $query, $customer_id)
    {
        if (! $customer_id) return $query;

        return $query->where('customer_id', $customer_id);
    }

    /**
     * @used-by filterDevice
     * @param Builder $query
     * @param $query_data
     * @return Builder
     */
    public function scopeFilterDevice(Builder $query, $query_data)
    {
        //判断 $query_data是否为空
        $implode_data = implode(',', $query_data);
        if (empty($implode_data)) return $query;

        return $query->whereHas('purchaseDevice', function(Builder $query) use($query_data){
            return $query->whereHas('device', function(Builder $query) use($query_data){
                return $this->assembleQuery($query,$query_data);
            });
        });
    }

    /**
     * @param Builder $query
     * @param $query_data
     * @return Builder|string
     */
    private function assembleQuery(Builder $query, $query_data)
    {
        foreach($query_data as $index => $value)
        {
            if (isset($value)) {
                $query->where($index,'like', '%'. $value.'%');
            }
        }

        return $query;
    }
}
